package org.springside.examples.showcase.wb.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.examples.showcase.wb.entity.TopKeyWord;
import org.springside.examples.showcase.wb.service.WbContentManager;
import org.springside.modules.utils.FreeMarkers;

import com.google.common.collect.Maps;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller
public class WbGraphController {
	@Autowired
	private WbContentManager wbContentManager;
	private Configuration cfg = FreeMarkers.buildConfiguration("classpath:/");

	@RequestMapping(value = "/graph/{pardate}/relation", method = RequestMethod.GET)
	public ResponseEntity<byte[]> downloadReportTemplateContent(@PathVariable("pardate") final String pardate) throws IOException {
		List<TopKeyWord> topKeyWords = wbContentManager.getTopKeyWords(pardate);
		for (TopKeyWord topKeyWord : topKeyWords) {
			System.out.println(topKeyWord.getKeyword() + ":" + topKeyWord.getWeight() + ":" + topKeyWord.getRef_mid());
		}
		Map<String, String> dataMap = Maps.newHashMap();
		Template template = cfg.getTemplate("gexf_template.ftl", "UTF-8");
		String result = FreeMarkers.renderTemplate(template, dataMap);
		byte[] bytes = result.getBytes("utf-8");
		HttpHeaders responseHeaders = httpHeader(bytes.length);
		return new ResponseEntity<byte[]>(bytes, responseHeaders, HttpStatus.OK);
	}

	public static HttpHeaders httpHeader(final int fileSize) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentType(MediaType.parseMediaType("application/octet-stream"));
		responseHeaders.set("Accept-Ranges", "bytes");
		responseHeaders.set("Content-Length", "" + fileSize);
		return responseHeaders;
	}

}
